//@author A0080442N
#include "TaskItTime.h"

TaskItTime::TaskItTime(){
	_display = EMPTY_FIELD;
	_originalDisplay = EMPTY_FIELD;
	_timeStorage = EMPTY_FIELD;
	_hasTime = false;
}

void TaskItTime::setTime(string timeString) {
	if(isValidTime(timeString)) {
		int timeInt = atoi(timeString.c_str());
		_min = timeInt % NUM_MOD_HUNDRED;
		_hour = (timeInt / NUM_MOD_HUNDRED) % NUM_MOD_HUNDRED;

		ostringstream display, originalDisplay;
		if(_hour < NUM_LESS_THAN_TEN) {
			display << NUM_0 << _hour << COLON;
			originalDisplay << NUM_0 << _hour;
		} else {
			display << _hour<< COLON;
			originalDisplay << _hour;
		}
		if(_min < NUM_LESS_THAN_TEN) {
			display << NUM_0 << _min;
			originalDisplay << NUM_0 << _min;
		} else {
			display << _min;
			originalDisplay << _min;
		}
		_display = display.str();
		_originalDisplay = originalDisplay.str();
		_timeStorage = timeString;
		_hasTime = true;
	} else {
		throw INVALID_TIME;
	}
}

bool TaskItTime::isValidTime(string timeString) {
	if(timeString.size() != TIME_SIZE) {
		return false;
	}
	
	for(int i = INITIAL_VALUE; i < TIME_SIZE; i++) {
		if(timeString[i] < NUM_0 || timeString[i] > NUM_9) {
			return false;
		}
	}
	
	int timeInt = atoi(timeString.c_str());
	
	if (timeInt < TIME_LOWER_BOUND || timeInt > TIME_UPPER_BOUND) {
		return false;
	} else {
		int hour, min;
		
		min = timeInt % NUM_MOD_HUNDRED;
		hour = (timeInt / NUM_MOD_HUNDRED) % NUM_MOD_HUNDRED;

		if (hour > HOURS_IN_DAYS || min > MINS_IN_HOURS) {
			return false;
		} 
	}
	return true;
}

bool TaskItTime::isLaterTime(TaskItTime secondTime) {
	if (_hasTime == false && secondTime.getHasTime() == false) {
		return false;
	} else if (_hasTime == false && secondTime.getHasTime() == true) {
		return false;
	}else if (_hasTime == true && secondTime.getHasTime() == false) {
		return true;
	} else if(secondTime.getHour() > _hour) {
		return false;
	} else if(secondTime.getHour() == _hour && secondTime.getMin() >= _min) {
		return false;
	}
	
	return true;
}

int TaskItTime::getHour() {
	return _hour;
}

int TaskItTime::getMin(){
	return _min;
}

string TaskItTime::getDisplay() {
	return _display;
}

string TaskItTime::getOriginalDisplay() {
	return _originalDisplay;
}

string TaskItTime::getTimeStorage(){
	return _timeStorage;
}

bool TaskItTime::getHasTime() {
	return _hasTime;
}

void TaskItTime::getLocalTime(){
	time_t now = time(INITIAL_VALUE);
	struct tm time;
	localtime_s(&time, &now);
	_hour = time.tm_hour;
	_min  = time.tm_min;
	ostringstream display;
	if(_hour < NUM_LESS_THAN_TEN) {
		display << NUM_0 << _hour << COLON;
	} else {
		display << _hour<< COLON;
	}
	if (_min < NUM_LESS_THAN_TEN) {
		display << NUM_0 << _min;
	} else {
		display << _min;
	}
	_display = display.str();
}